package com.easy.service.impl;


import com.easy.annotation.LogMethod;
import com.easy.bean.*;
import com.easy.mapper.OrderDetailMapper;
import com.easy.mapper.OrderMapper;
import com.easy.mapper.TicketMapper;
import com.easy.service.TicketService;
import com.easy.util.Page;
import com.easy.util.TicketInventoryManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 车票查询服务实现
 */
@Service
public class TicketServiceImpl implements TicketService {

    @Autowired
    private TicketMapper ticketMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    TicketInventoryManager ticketInventoryManager;

    @Override
    public List<TrainTicketQueryVO> queryTickets(TicketQueryParam param) {
        // 参数验证
        if (param == null || param.getFromStationName() == null || param.getToStationName() == null
                || param.getDepartDate() == null) {
            throw new IllegalArgumentException("查询参数不完整");
        }

        // 调用Mapper查询
        return ticketMapper.selectTickets(param);
    }

    @Override
//    @LogMethod(serviceName = "车票分页查询", recordParam = true, recordReturn = true)
    public void page(Page page, TicketQueryParam param) {
        int count = ticketMapper.pageCount(param);
        System.out.println("count:"+count);
        Object data = ticketMapper.page(page,param);
        page.setCount(count);
        page.setData(data);
    }

    @Override
    @LogMethod(serviceName = "车票生成订单", recordParam = true, recordReturn = true)
    public OrderDetail submit(OrderDetail param) {
        //内存数量扣除
        boolean b = ticketInventoryManager.deductTickets(param.getScheduleId(), 1);

        if (!b) {
            throw new RuntimeException("车票不足");
        }
        else{
            // 1. 生成UUID作为订单ID
            String orderId = UUID.randomUUID().toString().replace("-", "");
            param.setOrderId(orderId);
            // 2. 设置下单时间（当前时间）
            LocalDateTime now = LocalDateTime.now();
            param.setCreateTime(now);
            // 3. 设置锁定过期时间（当前时间+15分钟）
            param.setLockExpire(now.plusMinutes(15));
            long durationMinutes = java.time.Duration.between(param.getDepartTime(), param.getArriveTime()).toMinutes();
            param.setDurationMinutes((int) durationMinutes);


            // 4. 执行插入
            orderDetailMapper.add(param);
            OrderDetail result = orderDetailMapper.one(param.getId());
            Order order = new Order();
            order.setId(orderId);
            order.setUserId(param.getUserId());
            order.setScheduleId(param.getScheduleId());
            order.setCreateTime(param.getCreateTime());
            order.setLockExpire(param.getLockExpire());
            order.setStatus("未支付");
            orderMapper.add(order);

            System.out.println("下订单成功，剩余票数："+ticketInventoryManager.getRemainingTickets(param.getScheduleId()));

            return result;
        }
    }

    @Override
//    @LogMethod(serviceName = "指定日期车票剩余量", recordParam = true, recordReturn = true)
    public List<RemainTickets> getTicketStatisticsByDate(LocalDate date) {
        List<RemainTickets> rt = ticketMapper.getTicketStatisticsByDate(date);
        System.out.println(rt);
        return rt;
    }

//    // 每分钟检查一次过期订单
    @Scheduled(fixedRate = 1000*60)
    public void checkExpiredOrders() {
        // 查询已锁定且已过期的订单
        List<Order> expiredOrders = orderMapper.findExpiredOrders(LocalDateTime.now());
        System.out.println("检查过期订单expiredOrders:"+expiredOrders);
        for (Order order : expiredOrders) {
            // 更新订单状态为"已过期"
            orderMapper.timeOut(order.getId());
            orderDetailMapper.timeOut(order.getId());
            ticketInventoryManager.addTickets(order.getScheduleId(), 1);
        }
        System.out.println("已处理过期订单");
    }





}
